package com.example.interview.feizhu;

import com.example.leetcode.linkedlist.common.LinkedListUtils;
import com.example.leetcode.linkedlist.common.ListNode;

/**
 * 找到链表中间节点（两个时取后一个）
 */
public class timu1 {
    public static void main(String[] args) {
        timu1 timu1 = new timu1();

        int[] nums = {1, 2, 3, 4, 5};

        test(timu1, nums);

        int[] nums1 = {1, 2, 3, 4, 5, 6};
        test(timu1, nums1);

        int[] nums2 = {1};
        test(timu1, nums2);

        int[] nums3 = {1, 2};
        test(timu1, nums3);
    }

    private static void test(timu1 timu1, int[] nums) {
        ListNode head1 = LinkedListUtils.generateLinkedListByArray(nums);
        System.out.println(timu1.middleNode(head1).val);
    }

    public ListNode middleNode(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode left = head;
        ListNode right = head;
        while (right != null) {
            right = right.next;
            if (right != null) {
                right = right.next;
            } else {
                break;
            }
            left = left.next;
        }
        return left;
    }
}
